<!--
 * @Description: 电影院首页
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-05-30 12:01:39
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="bigbox">
    <view class="top">
      <image style="width: 120rpx; height: 50rpx" :src="handleShowImage()" />
      <view class="searchbox">
        <view class="searchbox-l">
          <view style="font-weight: 600; min-width: 150rpx">
            <u-dropdown style="min-width: 260rpx">
              <u-search
                v-model="searchCity"
                placeholder="搜索城市"
                @input="handleCityInput"
                :show-action="false"
                style="background-color: #fff; padding: 10rpx 20rpx"
              />
              <u-dropdown-item
                v-model="selectCityValue"
                :title="selectCityName"
                :options="filteredCityList"
                inactive-color="#000000"
                @change="handleChangeCity"
                :height="680"
              ></u-dropdown-item>
            </u-dropdown>
          </view>
          <text style="color: #dbdbdb; padding: 0rpx 10rpx">|</text>
        </view>
        <view class="searchbox-r">
          <u-search
            placeholder="请输入电影名"
            v-model="searchKey"
            clearabled
            :animation="false"
            :show-action="false"
            @search="handleSearchMovie"
            @clear="handleClearMovie"
          ></u-search>
        </view>
      </view>
      <!-- 重新加载图标 -->
      <u-icon
        name="reload"
        size="40"
        @click="handleReload"
        style="cursor: pointer"
      ></u-icon>
    </view>
    <view class="middle">
      <view class="middle-t">
        <view class="qpmbox" @click="handleGoCollectTicket">
          <view class="wz">
            <view class="qpm">取票码</view>
            <view class="ckqpm"
              >查看取票码
              <u-icon
                class="icon"
                name="play-right-fill"
                size="24"
                color="#e9962b"
              ></u-icon>
            </view>
          </view>
          <view class="tp">
            <image
              src="../../static/qpm.png"
              style="height: 90rpx; width: 90rpx"
            ></image>
          </view>
        </view>
        <view class="ddbox" @click="handleGoOrder">
          <view class="wz">
            <view class="dd">订单</view>
            <view class="ckdd"
              >查看订单详情
              <u-icon
                class="icon"
                name="play-right-fill"
                size="24"
                color="#8198EB"
              ></u-icon>
            </view>
          </view>
          <view class="tp">
            <image
              src="../../static/dd.png"
              style="height: 90rpx; width: 90rpx"
            ></image>
          </view>
        </view>
      </view>
      <view class="middle-b" style="margin: 20rpx 0">
        <van-tabs
          :active="activeIndex"
          @change="handleTabChange"
          color="#FF6C18"
          title-inactive-color="#999"
          title-active-color="#FF6C18"
        >
          <van-tab :title="`${wz.name}`" v-for="wz in wzList"></van-tab>
        </van-tabs>
      </view>
    </view>
    <view class="footer">
      <view class="showbox" v-if="activeIndex == 0">
        <template v-if="showHotMovieList.length > 0">
          <view
            class="item"
            v-for="dy in showHotMovieList"
            :key="dy.movieId"
            @click="handleGoDetail(dy)"
          >
            <view class="item-l">
              <van-image
                width="162rpx"
                height="232rpx"
                :src="dy.posterUrl"
                fit="cover"
              />
            </view>
            <view class="item-r">
              <view class="nr">
                <view class="bt overwz">{{ dy.movieName }} </view>
                <view class="xq">
                  <view
                    >评分：<text style="color: #ff6c18; font-size: 24rpx">
                      {{ dy.grade }}
                    </text></view
                  >
                  <view>{{ handleDate(dy.publishDate) }}上映</view>
                  <view class="overwz">导演：{{ dy.director }}</view>
                  <view class="overwz">主演：{{ dy.cast }}</view>
                </view>
              </view>
              <view class="btn">
                <u-button
                  type="primary"
                  shape="circle"
                  @click="handleGoSelectCinema(dy)"
                  >购票</u-button
                >
              </view>
            </view>
          </view>
          <u-back-top :scroll-top="scrollTop"></u-back-top>
        </template>
        <view v-else style="color: #999; text-align: center; font-size: 32rpx"
          >暂无影片</view
        >
      </view>
      <view class="showbox" v-if="activeIndex == 1">
        <template v-if="showPresaleMovieList.length > 0">
          <view
            class="item"
            v-for="dy in showPresaleMovieList"
            :key="dy.movieId"
            @click="handleGoDetail(dy)"
          >
            <view class="item-l">
              <van-image
                width="162rpx"
                height="232rpx"
                :src="dy.posterUrl"
                fit="cover"
              />
            </view>
            <view class="item-r">
              <view class="nr">
                <view class="bt overwz">{{ dy.movieName }} </view>
                <view class="xq">
                  <!-- <view
                    >评分：<text style="color: #ff6c18; font-size: 24rpx">
                      {{ dy.grade }}
                    </text></view
                  > -->
                  <view>{{ handleDate(dy.publishDate) }}上映</view>
                  <view>导演：{{ dy.director }}</view>
                  <view class="overwz">主演：{{ dy.cast }}</view>
                </view>
              </view>
              <!-- <view class="btn">
                <u-button
                  type="warning"
                  shape="circle"
                  style="background-color: #3b9dff"
                  @click="handleGoSelectCinema(dy)"
                  >预售</u-button
                >
              </view> -->
            </view>
          </view>
          <u-back-top :scroll-top="scrollTop"></u-back-top>
        </template>
        <view v-else style="color: #999; text-align: center; font-size: 32rpx"
          >暂无影片</view
        >
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, watch } from 'vue'
import { baseApi, movieApi } from '@/api'
import { getLocationInfo } from '@/utils/location'
import {
  onLoad,
  onShow,
  onReady,
  onReachBottom,
  onPageScroll
} from '@dcloudio/uni-app'
import { IMovie, IArea } from '@/packageF/components/movieInterface'
import { useMovieStore, useShopInfoStore } from '@/store/index'
import { handleCityData } from '../../components/movieUtil'
//图片
import hlhydy from '@/static/hlhydy.png'
import xfldy from '@/static/xfldy.png'
import cldy from '@/static/cldy.png'

const shopStore = useShopInfoStore()
const scrollTop = ref(0)
const movieStore = useMovieStore()
// 定义数据
const searchKey = ref('')
const selectCityName = ref<string | undefined>('定位中')
// 选择的城市id
const selectCityId = ref()
// 选择的城市的值，带city_
const selectCityValue = ref()
//点击tab的激活下标
const activeIndex = ref(0)
const cityList = ref<IArea[]>([])
const wzList = ref([
  {
    name: '正在热映'
  },
  {
    name: '即将上映'
  }
])
// 搜索的城市关键字
const searchCity = ref()
//热映影片原始数据
const hotMovieList = ref<IMovie[]>([])
// 预售影片原始数据
const presaleMovieList = ref<IMovie[]>([])
//热映影片展示数据
const showHotMovieList = ref<IMovie[]>([])
// 预售影片展示数据
const showPresaleMovieList = ref<IMovie[]>([])
const movieList = ref<IMovie[]>([])
// 是否是第一次获取城市
const isFirstGetCityName = ref(false)
let hasHandledLocation = false
// 所有的模式
const shopTypeAllList = ref([
  { name: '黑银', id: 0 },
  { name: '花积分', id: 1 },
  { name: '链动模式', id: 2 },
  { name: '酒慕网', id: 3 },
  { name: '鑫复来', id: 4 },
  { name: '长来科技', id: 6 }
])
// 是否获取到模式信息
const hasMovieMode = ref(false)
const movieShopMode = ref()

// 生命周期函数
onLoad(async (option: any) => {
  // console.log('触发首页', movieStore.xzCityName)
  console.log('首页option', option)
  // console.log('地区', uni.getStorageSync('allCityAndRegion'))
  // 新增检查：如果已经处理过定位，直接返回
  if (hasHandledLocation) return
  // 位置处理函数
  const handleLocation = async (result: any) => {
    if (hasHandledLocation) return // 确保只执行一次
    selectCityName.value = result.address.cityName.replace(/市$/, '')
    movieStore.setXzCityName(selectCityName.value)
    uni.setStorageSync('currentLocation', result.location)
    hasHandledLocation = true // 设置全局标志
    console.log('定位处理完成')
    if (selectCityName.value) {
      await getAllCityData()
    }
  }
  if (option?.from && option.from.toLowerCase() === 'app') {
    shopStore.setIsApp(true)
    // #ifdef H5
    // @ts-ignore
    window.JSBridge.registerEvent('HYUserEvent', async (data) => {
      // 双重检查
      if (hasHandledLocation) return
      console.log('收到 App 用户信息:', data)
      const result = await getLocationInfo()
      console.log('从app获取位置', result)
      await handleLocation(result)
    })
    // #endif
  } else {
    shopStore.setIsApp(false)
    const result = await getLocationInfo()
    console.log('位置', result)
    await handleLocation(result)
  }
  // 获取模式信息
  if (option.mode) {
    try {
      const modeArr = shopTypeAllList.value.filter(
        (item) => item.id == option.mode
      )
      console.log(JSON.stringify(modeArr[0]), modeArr)
      hasMovieMode.value = true
      movieShopMode.value = modeArr[0].id
      uni.setStorageSync('hyType', JSON.stringify(modeArr[0]))
    } catch (e) {
      console.error('序列化 hyType失败:', e)
    }
  } else {
    hasMovieMode.value = false
  }
})
onShow(async () => {
  console.log('首页状态机获取数据', movieStore.xzCityId, movieStore.xzCityName)
  handleInit()
  // 从状态机中获取到选择的城市id
  if (movieStore.xzCityId != 0 && movieStore.xzCityId != undefined) {
    // 复现城市名称
    selectCityName.value = movieStore.xzCityName
    // 复现城市下拉框
    selectCityValue.value = `city_${movieStore.xzCityId}`
  }
  getMovieList()
})

// 计算属性：根据搜索关键词过滤城市列表
const filteredCityList = computed(() => {
  if (!searchCity.value) return cityList.value
  return cityList.value.filter((item) =>
    item.cityName.includes(searchCity.value)
  )
})
watch(selectCityName, (newValue) => {
  console.log('selectCityName:', newValue)
})
watch(selectCityId, (newValue) => {
  console.log('selectCityId 变化:', newValue)
})

// 获取所有城市数据
const getAllCityData = async () => {
  uni.showLoading({ title: '加载中，请稍后', mask: true })
  try {
    const { data } = await movieApi.getAllCityAndRegionApi().finally(() => {
      uni.hideLoading()
    })
    // console.log(data, '所有地区数据')
    cityList.value = handleCityData(data)
    // console.log('99', handleCityData(data))
    // console.log('获取城市数据', selectCityName.value)
    if (cityList.value.length > 0) {
      //当不切换城市时，默认根据定位的城市名称获取到城市id并存储到状态机
      selectCityId.value = cityList.value.find(
        (ele: any) => ele.cityName == selectCityName.value
      )?.cityId
      movieStore.setXzCityId(selectCityId.value)
      // uni.setStorageSync('allCityAndRegion', JSON.stringify(cityList.value))
    } else {
      selectCityName.value = '成都'
      selectCityId.value = 8
      // 兜底成都
      movieStore.setXzCityName('成都')
      movieStore.setXzCityId(8)
    }
  } catch (e) {
    console.log('获取城市error', e)
  }
}
//获取影片数据
const getMovieList = async () => {
  uni.showLoading({ title: '加载中，请稍后', mask: true })
  try {
    const { data } = await movieApi.getAllMovieApi().finally(() => {
      uni.hideLoading()
    })
    movieList.value = data
    // console.log(data, '影片数据')
    hotMovieList.value = movieList.value.filter((ele: any) => {
      return ele.publishStatus == 'HOT'
    })
    showHotMovieList.value = [...hotMovieList.value]
    presaleMovieList.value = movieList.value.filter((ele: any) => {
      return ele.publishStatus == 'WAIT'
    })
    showPresaleMovieList.value = [...presaleMovieList.value]
  } catch (e) {
    console.log('获取影片失败', e)
  }
}
// 搜索城市
const handleCityInput = (e: any) => {
  searchCity.value = e
}
// 处理显示的图标
const handleShowImage = () => {
  switch (movieShopMode.value) {
    case 1:
      return hlhydy
    case 4:
      return xfldy
    case 6:
      return cldy
  }
}
// 通过电影名称搜索
const handleSearchMovie = () => {
  // 热映影片
  if (activeIndex.value == 0) {
    // 有关键词时进行过滤
    showHotMovieList.value = hotMovieList.value.filter((ele) => {
      return ele.movieName.includes(searchKey.value)
    })
  }
  // 预售影片
  if (activeIndex.value == 1) {
    showPresaleMovieList.value = presaleMovieList.value.filter((ele) => {
      return ele.movieName.includes(searchKey.value)
    })
  }
}
// 搜索电影的清除图标
const handleClearMovie = () => {
  // 热映影片
  if (activeIndex.value == 0) {
    // 有关键词时进行过滤
    showHotMovieList.value = [...hotMovieList.value]
  }
  // 预售影片
  if (activeIndex.value == 1) {
    showPresaleMovieList.value = [...presaleMovieList.value]
  }
}
// 切换tab
const handleTabChange = (index: any) => {
  activeIndex.value = index
  searchKey.value = ''
  if (index == 0) {
    showHotMovieList.value = [...hotMovieList.value]
  } else {
    showPresaleMovieList.value = [...presaleMovieList.value]
  }
}
// 城市下拉框发生改变
const handleChangeCity = (e: number) => {
  // e的值是city_cityId
  const findObj = cityList.value.find((ele: any) => ele.value == e)
  if (findObj) {
    selectCityId.value = findObj.cityId
    selectCityName.value = findObj.cityName
    movieStore.setXzCityId(findObj.cityId)
    movieStore.setXzCityName(findObj.cityName)
  }
}
// 处理日期格式
const handleDate = (date: string) => {
  const [year, monthStr, dayStr] = date.slice(0, 10).split('-')
  const month = parseInt(monthStr, 10)
  const day = parseInt(dayStr, 10)
  // 处理月份和天：小于10时直接显示数字，大于等于10时保持原样
  const formattedMonth = month < 10 ? month : month
  const formattedDay = day < 10 ? day : day
  // 返回格式化后的字符串
  return `${year}年${formattedMonth}月${formattedDay}日`
}
// 跳转取票页面
const handleGoCollectTicket = () => {
  uni.navigateTo({ url: `/packageF/pages/collectTicket/index` })
}
// 跳转订单页面
const handleGoOrder = () => {
  uni.navigateTo({ url: `/packageF/pages/movieOrder/index` })
}
// 点击购票跳转选择影院页面
const handleGoSelectCinema = (movieItem: any) => {
  if (hasMovieMode.value == false) {
    uni.showToast({
      title: '未获取到模式信息,请您退出该页面重新进入',
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: '/packageF/pages/selectCinema/index'
  })
  uni.setStorageSync('movieData', JSON.stringify(movieItem))
}
//点击电影盒子去详情
const handleGoDetail = (movieItem: any) => {
  if (hasMovieMode.value == false) {
    uni.showToast({
      title: '未获取到模式信息,请您退出该页面重新进入',
      icon: 'none'
    })
    return
  }
  // console.log('点击', movieItem)
  uni.navigateTo({
    url: `/packageF/components/movieDetails/index?data=${encodeURIComponent(
      JSON.stringify(movieItem)
    )}`
  })
}
// 初始化数据
const handleInit = () => {
  searchKey.value = ''
  if (activeIndex.value == 0) {
    showHotMovieList.value = []
  } else {
    showPresaleMovieList.value = []
  }
}
//返回顶部,所在的父盒子不能设置高度
onPageScroll((e: any) => {
  scrollTop.value = e.scrollTop
})
const handleReload = () => {
  getMovieList()
  getAllCityData()
}
</script>

<style lang="scss" scoped>
.bigbox {
  width: 750rpx;
  .top {
    width: 750rpx;
    height: 200rpx;
    background: white;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: auto;
    border-radius: 20rpx;
    box-shadow: 1rpx 3rpx #dbdbdb;
    padding: 0 10rpx;
    .searchbox {
      width: 680rpx;
      height: 72rpx;
      background: #f0f0f0;
      border-radius: 36rpx;
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding: 0 20rpx;
      .searchbox-l {
        display: flex;
        align-items: center;
      }
      .searchbox-r {
        text-align: left;
      }
    }
  }
  .middle {
    margin: 30rpx 0;
    width: 750rpx;
    .middle-t {
      display: flex;
      justify-content: space-around;
      align-items: center;
      .qpmbox,
      .ddbox {
        width: 340rpx;
        height: 110rpx;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: space-around;
        .wz {
          height: 110rpx;
          font-family: PingFangSC, PingFang SC;
          text-align: left;
          font-style: normal;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          align-items: flex-start;
        }
      }
      .qpmbox {
        background: linear-gradient(
          134deg,
          #fffcea 0%,
          #ffffff 29%,
          #ffe8c2 100%
        );
        .wz {
          .qpm {
            font-weight: 500;
            font-size: 24rpx;
            color: #da6c0a;
            line-height: 34rpx;
          }
          .ckqpm {
            font-weight: 400;
            font-size: 20rpx;
            color: #e9962b;
            line-height: 28rpx;
          }
        }
        .tp {
          width: 100rpx;
          height: 100rpx;
          // border: 1rpx dashed;
        }
      }
      .ddbox {
        background: linear-gradient(
          134deg,
          #e4ecff 0%,
          #ffffff 29%,
          #c9d9ff 100%
        );
        .wz {
          .dd {
            font-weight: 500;
            font-size: 24rpx;
            color: #6086ff;
            line-height: 34rpx;
          }
          .ckdd {
            font-weight: 400;
            font-size: 20rpx;
            color: #8198eb;
            line-height: 28rpx;
          }
        }
        .tp {
          width: 100rpx;
          height: 100rpx;
          // border: 1rpx dashed;
        }
      }
    }
  }
  .footer {
    margin-top: 40rpx;
    // height: 900rpx;
    overflow-y: scroll;
    .showbox {
      width: 702rpx;
      margin: 0 auto;
      .item {
        width: 702rpx;
        height: 268rpx;
        background: #ffffff;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        padding: 0 20rpx;
        margin-bottom: 20rpx;
        .item-l {
          width: 162rpx;
          height: 232rpx;
          border: 1rpx solid #dbdbdbdb;
          border-radius: 5rpx;
          margin-right: 10rpx;
        }
        .item-r {
          flex-grow: 1;
          height: 232rpx;
          display: flex;
          align-items: center;
          font-size: 24rpx;
          .nr {
            height: 100%;
            width: 0rpx;
            flex-grow: 1;
            margin-right: 20rpx;
            .bt {
              font-size: 32rpx;
              color: #000;
              font-weight: bold;
              margin-bottom: 20rpx;
            }
            .xq {
              color: #666666;
              > view {
                margin-bottom: 10rpx;
              }
            }
          }
          .btn {
            width: 112rpx;
            height: 50rpx;
          }
        }
      }
    }
  }
}
//修改下拉框遮罩层的高度
::v-deep .u-dropdown__content__mask {
  height: 50vh !important; /* 设置遮罩层高度为视口高度的50% */
  max-height: 50vh !important;
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
</style>
